import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox, ElSwitch } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'

import { agvList, addAgv, updateAgv, delAgv, UpdateStatus, agvModels, vehicletypes, agvBrand } from '@/utils/api/dispatch/agv'
import { GetAllMap } from '@/utils/api/dispatch/map'
import { GetAllStation } from '@/utils/api/dispatch/station'

export function useDept() {
  const form = reactive({
    agvname: "",
    ip: "",
    cehicletype: null,
    status: null,
    pageNumber: 0,
    pageSize: 10,
    sortName: "createtime",
    sortType: 0
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  var agvModel = ref([])
  var vehicletype = ref([])
  var mapTypes = ref([])
  var agvBrands = ref([])
  var chargingSelect = ref([])
  var stopSelect = ref([])
  // 状态
  function formatState(status) {
    const stateMap = {
      0: '禁用',
      1: '启用',
      2: '锁定',
    }
    return stateMap[status]
  }

  const columns: TableColumnList = [
    {
      label: "车辆名称",
      prop: "name",
      width: 110,
      align: "left",
      sortable: true
    },
    {
      label: "IP地址",
      prop: "ip",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "通讯端口",
      prop: "port",
      width: 110,
      align: "left",
      sortable: true
    },
    {
      label: "品牌",
      prop: "BrandName",
      width: 100,
      align: "left",
      sortable: true
    },
    {
      label: "型号",
      prop: "ModelName",
      width: 80,
      align: "left"
    },
    // {
    //   label: "车型",
    //   prop: "VehicleTypeName",
    //   width: 80,
    //   align: "left"
    // },
    {
      label: "适用地图",
      prop: "MapName",
      width: 110,
      align: "left"
    },
    {
      label: "行走高度",
      prop: "moveheight",
      width: 110,
      align: "left",
      sortable: true
    },
    {
      label: "载货行走高度",
      prop: "movelowheight",
      width: 140,
      align: "left",
      sortable: true
    },
    {
      label: "排序",
      prop: "sort",
      width: 100,
      align: "left"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {formatState(row.status)}
        </el-tag>
      )
    },
    {
      label: "备注",
      prop: "note",
      minWidth: 200,
      align: "left"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ]

  async function onSearch() {
    loading.value = true;
    const { Content } = await agvList(form);
    let newData = Content.Results;
    dataList.value = newData;
    pagination.total = Content.TotalCount;
    pagination.pageSize = Content.PageSize;
    pagination.currentPage = Content.PageNumber + 1;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {


    addDialog({
      title: `${title}车辆`,
      props: {
        formInline: {
          id: row?.id ?? null,
          name: row?.name ?? "",
          ip: row?.ip ?? "",
          port: row?.port ?? "",
          brand: row?.brand ?? "",
          moveheight: row?.moveheight ?? null,
          model: row?.model ?? null,
          movelowheight: row?.movelowheight ?? null,
          status: row?.status ?? 1,
          note: row?.note ?? "",
          vehicletype: row?.vehicletype ?? null,
          sort: row?.sort ?? null,
          mapid: row?.mapid ?? null,
          chargingpoint: (row?.chargingpoint && row?.chargingpoint?.split(',').map(Number)) ?? [],
          stoppoint: (row?.stoppoint && row?.stoppoint?.split(',').map(Number)) ?? []
        },
        agvModel: agvModel.value || [],
        vehicletype: vehicletype.value || [],
        mapTypes: mapTypes.value || [],
        agvBrands: agvBrands.value || [],
        chargingSelect: chargingSelect.value || [],
        stopSelect: stopSelect.value || []
      },
      width: "35%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(elForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            curData.chargingpoint = curData.chargingpoint.toString()
            curData.stoppoint = curData.stoppoint.toString()
            // 表单规则校验通过
            if (title === "新增") {
              delete curData.id
              addAgv(curData).then(res => {
                if (res.Code === 0) chores();
              })
            } else {
              let data = Object.assign(curData, { id: row.id })
              updateAgv(data).then(res => {
                if (res.Code === 0) chores();
              })
            }
          }
        });
      }
    })
  }

  // 删除
  function handleDelete(row) {
    // ElMessageBox({
    //   title: '提示',
    //   message: h('p', null, [
    //     h('p', null,`是否确认删除名称为${row.name}的数据项?`),
    //     h('p', { style: 'color: red' }, '会一同删除与之关联的数据！'),
    //   ]),
    // }).then(()=>{
    //   delAgv({id:row.id,deleteAll:1}).then(res => {
    //     if (res.Code === 0) {
    //       message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
    //       onSearch();
    //     }
    //   })
    // }).catch(() => { })
    ElMessageBox.confirm(
      `删除${row.name}时会一同删除与其关联的数据?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      delAgv({id:row.id,deleteAll:1}).then(res => {
        if (res.Code === 0) {
          message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  // 禁用/启用
  function handleStatus(row) {
    let typeName = row.status !== 1 ? '启用' : '禁用'
    ElMessageBox.confirm(
      `是否确认${typeName}名称为${row.name}的车辆?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      let state = row.status === 0 ? 1 : 0
      let data = { id: row.id, state }
      UpdateStatus(data).then(res => {
        if (res.Code === 0) {
          message(`您${row.status !== 0 ? '禁用' : '启用'}了名称为${row.name}的车辆`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    form.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.pageNumber = val - 1
    onSearch()
  }

  onMounted(async () => {
    let { Content: model } = await agvModels()
    agvModel.value = model
    let { Content: type } = await vehicletypes()
    vehicletype.value = type
    // 地图select
    let { Content: map } = await GetAllMap()
    mapTypes.value = map

    let { Content: brand } = await agvBrand()
    agvBrands.value = brand
    // 充电点
    let { Content: charging } = await GetAllStation({ status: 1, stationType: 2 })
    chargingSelect.value = charging
    // 充电点
    let { Content: stop } = await GetAllStation({ stationType: 1 })
    stopSelect.value = stop

    onSearch()
  })

  return {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    handleStatus
  }
}